import {Component, EventEmitter, Input, Output, QueryList, ViewChildren} from "@angular/core";
import {ActivityDetailProvider} from "../../../../providers/activity/activity-detail/activity-detail.provider";
import {ActivityClassify, ActivityStatus} from "../../../../model/pages/activity/activity-filter/activity-filter.model";
import {
    AddStaffTrack, RosterItem,
    TrackStatus
} from "../../../../model/pages/activity/roster-list/roster-list-item.model";
import {Events, NavController} from "ionic-angular";
import {CallNumber} from "@ionic-native/call-number";
import {CallNumberService} from "../../../../services/native/call-number/call-number.service";
import {
    RosterSortBy,
    SingleRosterFilterModel
} from "../../../../model/pages/activity/roster-filter/roster-filter.model";
import {RosterListProvider} from "../../../../providers/activity/roster-list/roster-list.provider";
import {ActivityListProvider} from "../../../../providers/activity/activity-list/activity-list.provider";
import * as _ from 'lodash';
import {ClientNoteEditProvider} from "../../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {ActivityRosterFilterPage} from "../../../../pages/activity/activity-roster-filter/activity-roster-filter";
import {LoadingService} from "../../../../services/common/loading.service";
import {RosterCardComponent} from "../roster-card/roster-card.component";
import {Vs} from "../../../../pages/activity/roster-list/vs";
import {AdpActionSheetController} from "../../../common/adp-action-sheet/adp-action-sheet-controller";

@Component({
    selector: 'roster-list',
    templateUrl: 'roster-list.component.html',
    providers: [ActivityDetailProvider, RosterListProvider,
        LoadingService,
        CallNumber, CallNumberService, ClientNoteEditProvider]
})
export class RosterListComponent {

    @Input() activity;
    @Input() classify;
    @Output() switch = new EventEmitter();

    constructor(private navCtrl: NavController,
                private adpActionSheetCtrl: AdpActionSheetController,
                private events: Events,
                private callNumber: CallNumber,
                private rosterPro: RosterListProvider,
                private activityListPro: ActivityListProvider,
                private callNumberService: CallNumberService,
                private loadingService: LoadingService) {
    }

    @ViewChildren(RosterCardComponent) rosterCards: QueryList<RosterCardComponent>;

    //是否展开排序条件
    private isExpandSorter: boolean = false;
    //筛选条件
    private rosterFil: SingleRosterFilterModel = new SingleRosterFilterModel();
    //筛选条件（用作展示）
    private tempFil: SingleRosterFilterModel = new SingleRosterFilterModel();
    //客户活动名单
    private rosterList: RosterItem[] = [];
    //当前试图 0代表客户名单，1代表增员名单
    private currentView = 0;
    //列表数据是否加载完毕
    private isLoaded = false;
    //排序方式
    private sortByList = [{
        val: RosterSortBy.priority,
        label: '默认排序'
    }, {
        val: RosterSortBy.name,
        label: '姓名'
    }];
    private cardListHeight = 0;
    private vs;
    private totalNum = 0;

    ngOnInit() {
        this.tempFil.classify = this.classify;
        this.rosterFil.classify = this.classify;
        this.subscribeEvents();
        this.getRosterList(null, true);
        this.computedCardListHeight();
        setTimeout(() => {
            document.querySelector('.roster-component-scroll')
                .addEventListener('scroll', () => {
                    this.vs.handleScrollEvent();
                    this.rosterList = this.vs.virtualArr;
                });
            this.rosterCards.changes.subscribe((res) => {
                if (this.vs && this.vs.changeIndexArr.length > 0) {
                    this.vs.updateDom();
                }
            });
        }, 0);
    }

    ngOnDestroy() {
        this.events.unsubscribe('activity-roster:search');
        this.events.unsubscribe('refresh roster');
    }

    computedCardListHeight() {
        this.cardListHeight = window.innerHeight - (0.176 * window.innerWidth) - (280 / 1080 * window.innerWidth);
    }

    //订阅筛选条件事件
    subscribeEvents() {
        this.events.subscribe('activity-roster:search', (res) => {
            this.rosterFil = _.cloneDeep(res);
            this.tempFil = _.cloneDeep(this.rosterFil);
            this.getRosterList(null, true);
        });
        this.events.subscribe('refresh roster', (detail) => {
            this.switchUserStatus(detail.id);
            // this.getRosterList(null, false);
        });
    }

    //补全参数（若活动状态，活动进度为空则补充为全量条件）
    supplementRosterFil() {
        if (this.rosterFil.trackStatus.length === 0) {
            if (this.rosterFil.classify === 0) {
                this.rosterFil.trackStatus = [TrackStatus.notFollow, TrackStatus.contacted,
                    TrackStatus.notContacted, TrackStatus.notInterested,
                    TrackStatus.waitCallback, TrackStatus.overInterview,
                    TrackStatus.overPrint, TrackStatus.complete];
            } else if (this.rosterFil.classify === 1) {
                this.rosterFil.trackStatus = [AddStaffTrack.notFollow, AddStaffTrack.process, AddStaffTrack.notIntend];
            }
        }
    }

    //切换筛选条件
    switchSotrBy(val) {
        this.rosterFil.sortBy = val;
        this.isExpandSorter = false;
        this.getRosterList(null, true);
    }

    getRosterList(refresh = null, needLoading = false) {
        if (needLoading) {
            this.loadingService.showLoading();
        }
        this.isLoaded = false;
        this.supplementRosterFil();
        this.rosterPro.getRosterListById(this.activity.id, this.rosterFil)
            .subscribe((res: RosterItem[]) => {
                this.storeRosterList(res);
                this.totalNum = res.length;
                this.vs = new Vs(res, '.component-card', '.roster-component-scroll', '.roster-component-card');
                this.rosterList = this.vs.initVirtualArr();
                this.isLoaded = true;
                if (refresh) {
                    refresh.complete();
                }
                if (needLoading) {
                    this.loadingService.dismissLoading();
                }
            }, err => {
                this.isLoaded = true;
                if (refresh) {
                    refresh.complete();
                }
                if (needLoading) {
                    this.loadingService.dismissLoading();
                }
            });
    }

    /**
     * @function 缓存列表
     * @author daniel wu
     * @param array
     */
    storeRosterList(array: any) {
        let storeList = [];
        if (array && array.length) {
            array.map(e => {
                storeList.push({
                    client_id: e.id,
                    name: e.name,
                    sex: e.sex || ''
                });
            });
        }
        window.sessionStorage.setItem('storeRosterList', JSON.stringify(storeList));
    }

    //展示切换状态选项
    showSelectAction(customerId, index, event) {
        let innerIndex = event.innerIndex;
        let activityId = event.innerId;
        let ev = event.$event;

        let status = this.rosterList[index].activitys[innerIndex].trackStatus;
        if (this.rosterFil.classify === ActivityClassify.marketActivity) {
            this.adpActionSheetCtrl.create({
                cssClass: 'roster-action',
                title: '跟进状态',
                buttons: [{
                    text: '未跟进',
                    cssClass: status === TrackStatus.notFollow ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: TrackStatus.notFollow
                        }, index, innerIndex);
                    }
                }, {
                    text: '已拨打',
                    cssClass: status === TrackStatus.contacted ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: TrackStatus.contacted
                        }, index, innerIndex);
                    }
                }, {
                    text: '未接通',
                    cssClass: status === TrackStatus.notContacted ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: TrackStatus.notContacted
                        }, index, innerIndex);
                    }
                }, {
                    text: '客户不感兴趣',
                    cssClass: status === TrackStatus.notInterested ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: TrackStatus.notInterested
                        }, index, innerIndex);
                    }
                }, {
                    text: '待回电',
                    cssClass: status === TrackStatus.waitCallback ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: TrackStatus.waitCallback
                        }, index, innerIndex);
                    }
                }, {
                    text: '已面谈',
                    cssClass: status === TrackStatus.overInterview ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: TrackStatus.overInterview
                        }, index, innerIndex);
                    }
                }, {
                    text: '已打印计划书',
                    cssClass: status === TrackStatus.overPrint ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: TrackStatus.overPrint
                        }, index, innerIndex);
                    }
                }, {
                    text: '已完成',
                    cssClass: status === TrackStatus.complete ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: TrackStatus.complete
                        }, index, innerIndex);
                    }
                }]
            }).present();
        } else {
            this.adpActionSheetCtrl.create({
                cssClass: 'roster-action',
                buttons: [{
                    text: '未跟进',
                    cssClass: status === AddStaffTrack.notFollow ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: AddStaffTrack.notFollow
                        }, index, innerIndex);
                    }
                }, {
                    text: '跟进中',
                    cssClass: status === AddStaffTrack.process ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: AddStaffTrack.process
                        }, index, innerIndex);
                    }
                }, {
                    text: '暂不跟进',
                    cssClass: status === AddStaffTrack.notIntend ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.switchStatus({
                            customerId,
                            activityId,
                            trackStatus: AddStaffTrack.notIntend
                        }, index, innerIndex);
                    }
                }]
            }).present();
        }
        ev.stopPropagation();
        setTimeout(() => {
            let nodeList = document.querySelectorAll('.roster-component-scroll');
            let len = nodeList.length;
            // console.log(nodeList[len - 1]);
            nodeList[len-1].scrollTop += 1;
        }, 10);
    }

    switchStatus(params, index, innerIndex) {
        this.rosterPro.switchRosterStatus(params).subscribe((res) => {
            this.rosterList[index].activitys[innerIndex].trackStatus = params.trackStatus;
        }, err => {
            console.log(err);
        });
        this.events.publish('update roster');
    }

    switchUserStatus(id) {
        this.rosterList.forEach((item) => {
            if (item.id === id) {
                item.activitys.forEach((innerItem) => {
                    if (innerItem.status === ActivityStatus.processing
                        && innerItem.trackStatus === TrackStatus.notFollow) {
                        innerItem.trackStatus = TrackStatus.contacted;
                    }
                })
            }
        })
        this.events.publish('update roster');
    }

    goToRosterFilter() {
        this.navCtrl.push('ActivityRosterFilterPage', {
            tempFil: _.cloneDeep(this.tempFil)
        });
    }

    goToRosterMap() {
        this.navCtrl.push('RosterMapPage', {origin: 'roster-list'});
    }

    expandSelect() {
        this.isExpandSorter = !this.isExpandSorter;
    }

    isOverTime(status) {
        return status === ActivityStatus.over;
    }

    emitSwitch(ev) {
        this.switch.emit(ev);
    }
}
